<?php

/**
 * Created by PhpStorm.
 * User: dapeng
 * Date: 2018/9/28
 * Time: 下午4:01
 * 封装数据库查询
 */
class MyPDO
{
    private $dbname = "test0925";
    private $host = "127.0.0.1";
    private $user = "root";
    private $pass = "";
    private $charts = "utf8";
    //成员变量 $db
    private $db = null;//存储连接数据库后的结果

    private static $instance = null;//单例的实例

    //在对象被实例化时进行默认操作
    private function __construct()
    {
        try{
           $config = include "config.php";
echo $config['a'];
        //连接数据库
        $this->db = new PDO("mysql:dbname=$this->dbname;host=$this->host","$this->user","$this->pass");
        $this->db->exec("set names $this->charts");
        //判断是否连接成功
        }catch (Exception $e){
            var_dump($e);
            die("连接失败");
        }
    }
    private function __clone(){}

    //获取单例的方法
    public static function getInstance(){
        if (self::$instance == null){
//            self::$instance = new MyPDO();//new self();
            self::$instance = new self();//new self();
        }
        return self::$instance;
    }

    //增
    function insert($sql){

       if($res = $this->db->exec($sql)){
           return $res;
       }else{
           var_dump($this->db->errorInfo());
           die();
       }
    }
    //删
    function delete($sql){
        if($res = $this->db->exec($sql)){
            return $res;
        }else{
            var_dump($this->db->errorInfo());
            die();
        }
    }
    //改
    function update($sql){
        if($res = $this->db->exec($sql)){
            return $res;
        }else{
            var_dump($this->db->errorInfo());
            die();
        }
    }
    //查
    function select($sql){
        //查询拿到的结果是一个PDO数据集合
        $pdoObject = $this->db->query($sql);
        //转成大家认识的关联数组
        $arr = [];
        foreach ($pdoObject as $item){
            array_push($arr,$item);
        }
        return $arr;
    }

}